package biznussoft.metercor.fragments;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.location.Location;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import biznussoft.metercor.MainActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.entity.AccountModel;
import biznussoft.metercor.entity.ServiceOrderModel;
import biznussoft.metercor.utils.Base64;
import biznussoft.metercor.utils.Session;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public  class ServiceOrderDetailsFragment extends Fragment  {
	private LocationListener mLocationListener;
	private LocationClient locationClient;
	private Double lat,lon;
	private TextView tvServiceName,tvServiceOrderId,tvAccount,tvBillAdress,tvContact,tvSiteStatus,tvContactEmail,
	tvPhone,tvPriority,tvStatus,tvEstimatedStart,tvEstimatedEnd;
	private String soAddress;
	private String mFileName,mImagePath,strImage,strSignature;
	private ImageView capturedImage,signatureImage,signatureCapture,imagecapture,save;
	private static final int RESULT_CAMERA = 1;
	private ServiceOrderModel mobel;        
	private RestClient client;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.service_order_details_fragment, null);
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {             
		super.onCreate(savedInstanceState);               
		setHasOptionsMenu(true);
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		MenuItem addAccount = menu.add("GetDirection");
		MenuItemCompat.setShowAsAction(addAccount, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		addAccount.setIcon(R.drawable.direction); 
		MenuItem gas = menu.add("Gas Meter");
		MenuItemCompat.setShowAsAction(gas, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		MenuItem water = menu.add("Water Meter");
		MenuItemCompat.setShowAsAction(water, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		super.onCreateOptionsMenu(menu, inflater);
	}                         
	
	
	@Override
	 public boolean onOptionsItemSelected(MenuItem item) {
		
		 if(item.getTitle().equals("GetDirection")){
			 MyLocationManager loc = new MyLocationManager(getActivity());
			 loc.getLocations();
		 }
		 if(item.getTitle().equals("Water Meter")){

	            
				WatermeterDetailsFragment newFragment = new WatermeterDetailsFragment();
				FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
				transaction.replace(R.id.fragment2, newFragment);
				transaction.addToBackStack(null);
				transaction.commit();
				new Handler().postDelayed(new Runnable() {                      
					@Override
					public void run() {
						WatermeterDetailsFragment warehouseFragment = (WatermeterDetailsFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment2);
						//warehouseFragment.getWarehouseDetails();
					}
				}, 1000);
			
				
		 }
		 if(item.getTitle().equals("Gas Meter")){

	            
				GasMeterDetailsFragment newFragment = new GasMeterDetailsFragment();
				FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
				transaction.replace(R.id.fragment2, newFragment);
				transaction.addToBackStack(null);
				transaction.commit();
				new Handler().postDelayed(new Runnable() {                      
					@Override
					public void run() {
						GasMeterDetailsFragment warehouseFragment = (GasMeterDetailsFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment2);
						//warehouseFragment.getWarehouseDetails());
					}
				}, 1000);
			
					
				
		 }
		
		 return super.onOptionsItemSelected(item);             
	 }
	
	@Override
	public void onAttach(Activity activity) {          
		super.onAttach(activity);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	
		client =  MainActivity.mActivity.client;
		signatureCapture = (ImageView) getView().findViewById(R.id.addSignature);
		imagecapture = (ImageView) getView().findViewById(R.id.captureImage);
		capturedImage = (ImageView) getView().findViewById(R.id.image);
		signatureImage = (ImageView) getView().findViewById(R.id.signature);
		capturedImage.setVisibility(View.GONE);
		signatureImage.setVisibility(View.GONE);
		save = (ImageView) getView().findViewById(R.id.Submit);
		save.setVisibility(View.GONE);
		save.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				attachSignature();
				attachImage();  
			}
		});
		tvServiceOrderId = (TextView) getView().findViewById(R.id.tvorderid);
		tvSiteStatus = (TextView) getView().findViewById(R.id.tvSiteStatus);
		tvAccount = (TextView) getView().findViewById(R.id.tvAccount);
		tvBillAdress = (TextView) getView().findViewById(R.id.tvBilltoaddress);
		tvContact = (TextView) getView().findViewById(R.id.tvContact);   
		tvContactEmail = (TextView) getView().findViewById(R.id.tvContactEmail);
		tvServiceName = (TextView) getView().findViewById(R.id.tvService);
		tvPhone = (TextView) getView().findViewById(R.id.tvPhone);
		tvPriority = (TextView) getView().findViewById(R.id.tvPriority);
		tvStatus = (TextView) getView().findViewById(R.id.tvStatus);
		tvEstimatedStart = (TextView) getView().findViewById(R.id.tvestimatedStart);
		tvEstimatedEnd = (TextView) getView().findViewById(R.id.tvestimatedEnd);
		
		mFileName = "image"+".jpg";
		mImagePath = Environment.getExternalStoragePublicDirectory("download")+"/fs360/";
		
		signatureCapture.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				signatureImage.setVisibility(View.VISIBLE);
				save.setVisibility(View.VISIBLE);
				signatureCapture();
			}
		});

		imagecapture.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				capturedImage.setVisibility(View.VISIBLE);
				save.setVisibility(View.VISIBLE);
				imageCapture();            
			}
		});
	}
	
	public void attachSignature(){
		String objectType = "Attachment";
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("ParentId",Session.sSerOrderId);
		fields.put("Name","Signature Capture.png");
		fields.put("Body",strSignature);                                                                                                                                            
		try {
			RestRequest restRequest = RestRequest.getRequestForCreate(AccountModel.api_Version,objectType,fields);
			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {     
						Log.i("NCS","result is   :"+result);            
					}                                
					catch (Exception e) {
						Log.i("NCS","Exception is   :"+e.getMessage());
					}
				}
				//@Override
				public void onError(Exception exception) {
					
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});             
		} 
		catch (Exception e) {
			Log.i("NCS","Exception is   :"+e.getMessage());

		}

	
	
	}
	
	public void attachImage(){
		String objectType = "Attachment";
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("ParentId",Session.sSerOrderId);
		fields.put("Name","Photo.png");
		fields.put("Body",strImage);                                                                                                                                            
		try {
			RestRequest restRequest = RestRequest.getRequestForCreate(AccountModel.api_Version,objectType,fields);
			Log.i("NCS","Service   is :"+fields);
			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {     
						if(result.toString().contains("true")){                       
						getActivity().getSupportFragmentManager().beginTransaction().remove(ServiceOrderDetailsFragment.this).commit();}
					}                                
					catch (Exception exception) {

					}
				}
				//@Override
				public void onError(Exception exception) {
					
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});             
		} 
		catch (Exception e) {
			Log.i("NCS","Exception is   :"+e.getMessage());
		}

	
	
	}
	
	
	public void getSignature(String signature){
		try{
			strSignature = signature;
			byte[] decodedString = Base64.decode(signature);
			Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
			signatureImage.setImageBitmap(decodedByte);
		}catch (Exception e) {
		}
	}
	public void signatureCapture(){

		ServiceOrderSignature.newInstace().show(getActivity().getSupportFragmentManager(), "dialog");
	}
	public void imageCapture(){

		File file = checkFileExistence(mImagePath, mFileName);
		init_Camera(file);

	}

	public static File checkFileExistence(String path, String fileName) {
		if (!new File(path).exists()) {
			new File(path).mkdirs();
		}
		File file = new File(path, fileName);
		return file;
	}                

	public void init_Camera(File file) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		startActivityForResult(intent,RESULT_CAMERA);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			try {
				UpdateUIWithImages(mFileName);
			} catch (Exception e) {
				Log.i("Today","Display Image"+e.getMessage());
			}
		}
	}

	private void UpdateUIWithImages(String fileName) throws Exception {

		File file = new File(mImagePath+"/"+fileName);
		Bitmap bitmap  = getFileFromStorage(file);
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
		byte[] imagebyte = stream.toByteArray();             
		strImage = Base64.encodeBytes(imagebyte);     
		byte[] decodedString = Base64.decode(strImage);
		Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
		capturedImage.setImageBitmap(decodedByte);  
	}

	private Bitmap getFileFromStorage(File file) throws Exception {
		try {
			// decode image size
			Bitmap retBmp = null;
			System.gc();
			int scale = 1;
			if (file.length() > 400000) {
				scale = 4;
			} else if (file.length() > 100000 && file.length() < 400000) {
				scale = 2;
			}
			// decode with inSampleSize
			if (file.exists()) {
				BitmapFactory.Options bitmapFactoryObject = new BitmapFactory.Options();
				bitmapFactoryObject.inSampleSize = scale;
				retBmp = BitmapFactory.decodeFile(file.getPath(), bitmapFactoryObject);
			}

			return rotateImage(retBmp, file.getPath());
		} catch (Exception t) {
			t.printStackTrace();
			// CustomLogHandler.printErrorlog(t);
			throw new Exception(
					"Today"
							+ " Error in getFileFromStorage(File p_file) of ImageLoader",
							t);
		}
	}
	private Bitmap rotateImage(Bitmap decodedbitMap, String path) throws Exception {
		try {
			ExifInterface exif = new ExifInterface(path);
			String orientString = exif
					.getAttribute(ExifInterface.TAG_ORIENTATION);
			int orientation = orientString != null ? Integer
					.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL;
					int rotationAngle = 0;
					if (orientation == ExifInterface.ORIENTATION_ROTATE_90)
						rotationAngle = 90;
					if (orientation == ExifInterface.ORIENTATION_ROTATE_180)
						rotationAngle = 180;
					if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
						rotationAngle = 270;

					Matrix matrix = new Matrix();
					matrix.setRotate(rotationAngle);
					Bitmap rotatedBitmap = Bitmap.createBitmap(decodedbitMap, 0, 0,
							decodedbitMap.getWidth(), decodedbitMap.getHeight(), matrix, true);
					//
					FileOutputStream fileOutputStream = new FileOutputStream(path);
					rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 50,
							fileOutputStream);

					return rotatedBitmap;

		}

		catch (Throwable t) {
			// CustomLogHandler.printErrorlog(t);
			throw new Exception("Today" + " Error in rotateImage:", t);
		}

	}
	
	public void getWarehouseDetails(int Position){      
		
		mobel = ServiceOrderRecordsFragment.serviceOrderList.get(Position);
		tvServiceOrderId.setText(mobel.getName());
		tvSiteStatus.setText(mobel.getSiteStatus());
		tvServiceName.setText(mobel.getServiceName());
		tvAccount.setText(mobel.getAccountName());
		tvContact.setText(mobel.getContactName());
		tvContactEmail.setText(mobel.getContatEmail());
		tvEstimatedEnd.setText(mobel.getEstimatedEndDate());
		tvEstimatedStart.setText(mobel.getEstimatedStartDate());                           
		tvStatus.setText(mobel.getStatus());
		tvBillAdress.setText(mobel.getBillToAddress());
		soAddress = mobel.getBillToAddress();
		tvPhone.setText(mobel.getAlternatePhone());
		tvPriority.setText(mobel.getPriority());
		
	}

	
	
	

	
	
	  class MyLocationManager implements OnConnectionFailedListener ,ConnectionCallbacks{
	    	public Location location;
	    	private Context mContext;
	    	
	    	public MyLocationManager(Context context) {

	    		mContext = context;
	    	}

	    	public void getLocations() {
	    				 locationClient = new LocationClient(mContext, this, this);
	    				 locationClient.connect();
	    			}

	    	public void onConnected(Bundle connectionHint) {
	    		
	    			LocationRequest lRequest = LocationRequest.create().setInterval(1000).setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
	    			 mLocationListener = new LocationListener() {
	    				
	    				public void onLocationChanged(Location location) {
	    					lat = location.getLatitude();
	    					lon = location.getLongitude();
	    					new MyAsynTask().execute();
	    				}   
	    			};
	    			
	    			locationClient.requestLocationUpdates(lRequest, mLocationListener);
	    			
	    			
	    	}

	    	public void onDisconnected() {
	    		
	    	}

	    	public void onConnectionFailed(ConnectionResult result) {
	    		
	    	}
	    }
	
	
	  public class MyAsynTask extends AsyncTask<Void, Void, Void>{

			@Override
			protected Void doInBackground(Void... params) {
				  try {
					  getLocationInfo(lat, lon);
		            } catch (Exception e) {
		                e.printStackTrace();
		            }
				return null;
			}
	    	
	    }
	  
	  
	  public  JSONObject getLocationInfo(Double lat,Double lon) {

			HttpGet httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=false");
			HttpClient client = new DefaultHttpClient();
			HttpResponse response;
			StringBuilder stringBuilder = new StringBuilder();

			try {
				response = client.execute(httpGet);
				HttpEntity entity = response.getEntity();
				InputStream stream = entity.getContent();
				int b;
				while ((b = stream.read()) != -1) {
					stringBuilder.append((char) b);
				}
			} catch (ClientProtocolException e) {
			} catch (IOException e) {
			}

			JSONObject jsonObject = new JSONObject();
			
			try {
				jsonObject = new JSONObject(stringBuilder.toString());
				getGeoPoint(jsonObject);
			} catch (JSONException e) {
				Log.i("NCS", "Exception 1 is  :  " + e.getMessage());
			}
			                             
			
			return jsonObject;
		}
		
	  
	  public  void getGeoPoint(JSONObject jsonObject) {

			
			try {
				locationClient.removeLocationUpdates(mLocationListener);
				JSONArray results = jsonObject.getJSONArray("results");
				JSONObject js = results.getJSONObject(0);
				String adress = js.getString("formatted_address");

				/*String uri = "http://maps.google.com/maps?saddr="+adress+"&daddr="+"Begumpet, Hyderabad, Andhra Pradesh";
				 Intent i = new  Intent(Intent.ACTION_VIEW,Uri.parse("geo:0,0?q="+"Begumpet, Hyderabad, Andhra Pradesh"));       
				Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
				intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
				startActivity(i); */
				String uri = "http://maps.google.com/maps?saddr="+adress+"&daddr="+soAddress;
				Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
				intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
				startActivity(intent);    
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}


		}

	
}
